"""
    创建应用程序,并注册相关蓝图
"""
from flask import Flask
from app.models.base import db

from app.models.base import db
from app.common.email import mail
from flask import Response, jsonify

from flask_login import LoginManager
from flask.ext.pymongo import PyMongo
class MyResponse(Response):
    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, (list, dict)):
            response = jsonify(response)
        return super(Response, cls).force_type(response, environ)

login_manager = LoginManager()
mongo = PyMongo()
def create_app(config=None):
    app = Flask(__name__,static_folder="statics")
    app.response_class = MyResponse

    # Load default configuration
    app.config.from_object('app.conf.settings')
    app.config.from_object('app.conf.secure')

    # 注册SQLAlchemy
    db.init_app(app)
    # 注册蓝图
    register_web_blueprint(app)

    # 注册email模块
    mail.init_app(app)

    mongo.init_app(app)
    # 注册login模块
    login_manager.init_app(app)
    login_manager.login_view = 'web.forbid'
    login_manager.login_message = '请先登录或注册'

    # 额外配置处理
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)
    return app


def register_web_blueprint(app):
    from app.web import web
    app.register_blueprint(web)
